/**
 * @Description:主要用于获取带值的参数 远程查询下拉会特殊处理
 */

import { deepClone, isNotEmpty, isTableById } from '@/utils/util'
import { BASE_TYPE } from '@/utils/constants'
import {
  isBetween,
  isIn,
  isLe,
  isLike,
  isMissingvalue,
  isNear,
  isTag,
} from '@/components/event-behavior/query/utils'
import { isArray } from 'xe-utils'

export function getQueryValue(arr) {
  let widget = null
  if (!arr || arr.length < 2) {
    return null
  }
  if (arr[0] == '1') {
    // 获取页面入参
    // return getPageParams(arr[1])
    return null
  } else if (arr[0] == '2') {
    widget = this.getWidgetRef(arr[1])
    if (!widget) {
      console.error(`获取组件时错误。组件id: ${arr[1]}`)
      return null
    } else {
      if (isTableById(arr[1])) {
      } else {
        let value = widget?.getValue()
        const field = widget.field
        if (field.type === 'select' && field.options.remote) {
          console.log('select远程数据', value)
          value = widget.searchValue
        }
        // 其他组件直接返回value
        return value
      }
    }
  }
}

/**
 * 获取分页信息
 * @param value 参数的值
 */
function getPagination(value) {
  let pagination = null
  if (value[0] == 2) {
    if (isTableById(value[1])) {
      pagination = {
        pageNumber: this.getWidgetRef(value[1], '分页处理pageNumber错误').currentPage,
        pageSize: this.getWidgetRef(value[1], '分页处理pageSize错误').pageSize,
      }
    }
  }
  return pagination
}

/**
 * 格式化baseType=query的参数查询条件
 * @param item
 */
function formatQueryData(item) {
  let query = {
    permit: item.permit || '',
    filters: item.conditionList ? changeQueryData.call(this, deepClone(item.conditionList)) : {},
    sorts: item.sortList ? deepClone(item.sortList) : [],
  }
  query.pagination = formatPagination.call(this, item)
  return JSON.stringify(query)
}

function formatPagination(item) {
  let pagination = undefined
  if (item.pagination && item.pagination.enabled) {
    pagination = {}
    if (item.pagination.isFrom == '2') {
      pagination.pageNumber = getPagination.call(this, item.pagination.pageFrom).pageNumber ?? ''
      pagination.pageSize = getPagination.call(this, item.pagination.pageSizeFrom).pageSize ?? ''
    } else {
      pagination.pageNumber = item.pagination.pageNumber
      pagination.pageSize = item.pagination.pageSize
    }
  }
  return pagination
}

/**
 * 获取所有绑定了组件或者页面入参的请求参数和infoTable参数本身(不包括infoTable下的参数)
 * @param params
 * @returns {*}
 */
export function getNotEmptyReuqeustParam(params) {
  const isQuery = (value) => isNotEmpty(value) && isNotEmpty(value?.filters)
  return params.filter(
    (item) =>
      item?.value &&
      ((isNotEmpty(item.value) && !item.isChild) ||
        isQuery(item.value) ||
        item.baseType === BASE_TYPE.INFOTABLE)
  )
}

/**
 * 递归处理baseType==query的fitlers数组
 * @param data
 * @returns {{}}
 */
function changeQueryData(data) {
  let res = {}
  if (data && Object.keys(data).length !== 0) {
    if (Object.keys(data).includes('filters')) {
      let temp = deepClone(data.filters)
      res.type = data.type
      res.filters = temp.map((item) => {
        return changeQueryData.call(this, item)
      })
    } else {
      res = getFilterData.call(this, data)
    }
  }
  return res
}

/**
 * 获取fitlers参数中filter的值
 * @param data
 * @returns {{}}
 */
function getFilterData(data) {
  let res = {}
  if (isLike(data.type) || isLe(data.type)) {
    res = {
      fieldName: data.fieldName,
      type: data.type,
      value: data.value,
      isCaseSensitive: data.isCaseSensitive,
    }
    if (data.isFrom == '2') {
      res.value = isLike(data.type)
        ? `*${getQueryValue.call(this, data.from) || ''}*`
        : `${getQueryValue.call(this, data.from) ? getQueryValue.call(this, data.from) : ''}`
    }
  } else if (isBetween(data.type)) {
    res = {
      fieldName: data.fieldName,
      type: data.type,
      from: data.between.from,
      to: data.between.to,
    }
    if (data.between.isStartFrom == '2') {
      res.from = getQueryValue.call(this, data.startFrom) ?? ''
    }
    if (data.between.isEndFrom == '2') {
      res.to = getQueryValue.call(this, data.endFrom) ?? ''
    }
  } else if (isIn(data.type)) {
    res = {
      fieldName: data.fieldName,
      type: data.type,
      value: data.in.values,
      isCaseSensitive: data.isCaseSensitive,
    }
    if (data.isFrom == '2') {
      res.value = getQueryValue.call(this, data.from) ?? []
    }
  } else if (isMissingvalue(data.type)) {
    res = {
      fieldName: data.fieldName,
      type: data.type,
    }
  } else if (isNear(data.type)) {
    res = {
      fieldName: data.fieldName,
      type: data.type,
      location: data.near.location,
      distance: data.near.distance,
      units: data.near.units,
    }
  } else if (isTag(data.type)) {
    res = {
      fieldName: data.fieldName,
      type: data.type,
      tags: data.tag.tags ? JSON.parse(data.tag.tags) : [],
    }
  }
  return res
}

/**
 * 获取组件值到服务注册参数中
 * 获取服务参数中所有绑定了组件的参数，将参数遍历，按参数类型进行匹配
 * item.value[0]==2代表是绑定了组件的参数
 */
export function getComponentValueToService(curService) {
  const params = getNotEmptyReuqeustParam(curService.parameterDefinitions)
  const requestParams = {}
  // console.log('getComponentValueToService', params);
  params.forEach((item) => {
    try {
      switch (item.baseType) {
        case BASE_TYPE.STRING:
        case BASE_TYPE.NUMBER:
        case BASE_TYPE.BOOLEAN:
          if (!item.isChild) {
            if (item.value[0] == 2) {
              requestParams[item.name] = getQueryValue.call(this, item.value)
            } else if (item.value[0] == 3) {
              requestParams[item.name] = item.fixedValue
            }
          }
          break
        case BASE_TYPE.QUERY:
          requestParams[item.name] = formatQueryData.call(this, item)
          break
        case BASE_TYPE.INFOTABLE:
          if (item.baseType === BASE_TYPE.INFO_TABLE) {
            let childArr = curService.parameterDefinitions.filter(
              (child) => child.isChild && child.parentName === item.name
            )
            let childObj = {}
            let fieldDefinitions = {}
            childArr.forEach((child) => {
              if (isArray(child.value)) {
                if (child.value[0] == 2) {
                  childObj[child.name] = getQueryValue.call(this, child.value)
                } else if (child.value[0] == 3) {
                  childObj[child.name] = child.fixedValue
                }
              }
              fieldDefinitions[child.name] = { ...child }
            })
            if (childObj) {
              requestParams[item.name] = {
                dataModel: { fieldDefinitions: fieldDefinitions },
                rows: [childObj],
              }
            }
          }
          break
      }
    } catch (err) {
      console.error(`读取数据源 **${curService.name}** 失败, 错误参数${item.name}`)
    }
  })
  return requestParams
}

export function transforComponentValueMapToPostParam(curService, componentValueMap) {
  console.log('transforComponentValueMapToPostParam', curService)
  const dataModel = curService.fieldDefinitions
  const rows = [componentValueMap]
  return {
    values: {
      dataModel,
      rows,
    },
  }
}
